import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),

      home: ImageSelectExample(),
    );
  }
}

class ImageSelectExample extends StatefulWidget {
  const ImageSelectExample({super.key});

  @override
  _ImageSelectExampleState createState() => _ImageSelectExampleState();
}

class _ImageSelectExampleState extends State<ImageSelectExample> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('相册相机')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _selectImage == null
                ? SizedBox()
                : Image.file(_selectImage!, width: 100),

            SizedBox(height: 40),

            ElevatedButton(
              onPressed: () {
                checkGalleryPermisson();
              },
              child: Text('相册选择（权限）'),
            ),
            SizedBox(height: 40),
            ElevatedButton(
              onPressed: () {
                checkPermisson();
              },
              child: Text('拍照（权限）'),
            ),
            SizedBox(height: 40),

            ElevatedButton(
              onPressed: () {
                gallerySelectAndPress();
              },
              child: Text('相册选择（压缩）'),
            ),
          ],
        ),
      ),
    );
  }

  //选择照片 并压缩
  void gallerySelectAndPress() async {
    ImagePicker _imagePicker = ImagePicker();
    XFile? xifle = await _imagePicker.pickImage(source: ImageSource.gallery);
    if (xifle == null) {
      return;
    }
    //选择
    //压缩
    XFile? pressXfile = await compressImageFonction(xifle);
  }

  Future<XFile?> compressImageFonction(XFile oriFile) async {
    //临时目录
    final Directory temDirectory = await getTemporaryDirectory();
    final tempPath = temDirectory.path;
    //生成新的文件路径
    final tagetPath =
        '$tempPath/${DateTime.now().millisecondsSinceEpoch}_commpressed.jpg';
    //压缩
    XFile? xfile = await FlutterImageCompress.compressAndGetFile(
      oriFile.path,
      tagetPath,
      quality: 50,
      minWidth: 1080,
      minHeight: 1920,
    );
    if (xfile == null) {
      return null;
    }

    print('原图的大小  ${await oriFile.length() ~/ 1024} KB');
    print('新图的大小  ${await xfile.length() ~/ 1024} KB');
    return xfile;
  }

  File? _selectImage;

  void checkGalleryPermisson() async {
    if (Platform.isIOS) {
      selectImage();
      return;
    }
    //

    //校验一下
    late PermissionStatus status;

    //android 13
    bool isAndroid13 = await checkIsAndroid();
    if (isAndroid13) {
      status = await Permission.photos.status;
    } else {
      status = await Permission.storage.status;
    }

    if (status.isGranted) {
      selectImage();
      return;
    }
    if (status.isDenied) {
      //拒绝过一次 可以再次申请
      //弹框
      dynamic res = await showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('说明'),
            content: Text("需要使用您 的相册 设置头像功能 "),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("取消"),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("同意"),
              ),
            ],
          );
        },
      );

      if (res == null || !res) {
        return;
      }
      //执行  权限申请
      late PermissionStatus newStatus;
      if (isAndroid13) {
        newStatus = await Permission.photos.request();
      } else {
        newStatus = await Permission.storage.request();
      }
      if (newStatus.isGranted) {
        selectImage();
        return;
      }
      return;
    } else if (status.isPermanentlyDenied) {
      //永久拒绝 不可再次申请
      //跳转设置中心开启
      dynamic res = await showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('说明'),
            content: Text("需要使用您 的相机来拍照 设置头像功能,需要跳转设置中心 "),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("取消"),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("同意"),
              ),
            ],
          );
        },
      );
      if (res == null || !res) {
        return;
      }

      openAppSettings();
      return;
    }
    //弹框 申请权限的用途
    //动态申请
    late PermissionStatus newStatus;
    if (isAndroid13) {
      newStatus = await Permission.photos.request();
    } else {
      newStatus = await Permission.storage.request();
    }
  }

  void selectImage() async {
    ImagePicker _imagePicker = ImagePicker();
    XFile? xfile = await _imagePicker.pickImage(source: ImageSource.gallery);
    if (xfile == null) {
      return;
    }
    _selectImage = File(xfile.path);
    _compressImage(_selectImage!);

    setState(() {});
  }

  // 2. 核心压缩方法
  Future<XFile?> _compressImage(File file) async {
    // 获取应用临时目录
    final tempDir = await getTemporaryDirectory();
    final tempPath = tempDir.path;
    // 生成压缩后的文件路径
    final targetPath =
        '$tempPath/${DateTime.now().millisecondsSinceEpoch}_compressed.jpg';

    // 使用 flutter_image_compress 进行压缩
    XFile? result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      quality:
          70, // 压缩质量 (0-100)，通常 70-85 较平衡 [citation:1][citation:6][citation:8]
      minWidth: 1080, // 设置图片最小宽度 [citation:2][citation:6][citation:8]
      minHeight: 1920, // 设置图片最小高度 [citation:2][citation:6][citation:8]
    );

    // 打印原图和压缩后的大小，方便对比
    print("原图大小: ${file.lengthSync() ~/ 1024} KB");
    if (result != null) {
      print("压缩后大小: ${await result.length() ~/ 1024} KB");
    }

    return result;
  }

  void checkPermisson() async {
    if (Platform.isIOS) {
      takePhone();
      return;
    }
    //校验一下
    PermissionStatus status = await Permission.camera.status;
    if (status.isGranted) {
      takePhone();
      return;
    }
    if (status.isDenied) {
      //拒绝过一次 可以再次申请
      //弹框
      dynamic res = await showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('说明'),
            content: Text("需要使用您 的相机来拍照 设置头像功能 "),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("取消"),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("同意"),
              ),
            ],
          );
        },
      );

      if (res == null || !res) {
        return;
      }
      //执行  权限申请
      PermissionStatus newStatus = await Permission.camera.request();
      if (newStatus.isGranted) {
        takePhone();
        return;
      }
      return;
    } else if (status.isPermanentlyDenied) {
      //永久拒绝 不可再次申请
      //跳转设置中心开启
      dynamic res = await showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('说明'),
            content: Text("需要使用您 的相机来拍照 设置头像功能,需要跳转设置中心 "),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("取消"),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
                child: Text("同意"),
              ),
            ],
          );
        },
      );
      if (res == null || !res) {
        return;
      }

      openAppSettings();
      return;
    }
    //弹框 申请权限的用途
    //动态申请
    PermissionStatus newStatus = await Permission.camera.request();
  }

  void takePhone() async {
    ImagePicker _imagePicker = ImagePicker();
    XFile? xifile = await _imagePicker.pickImage(source: ImageSource.camera);

    if (xifile == null) {
      return;
    }

    _selectImage = File(xifile.path);

    setState(() {});
  }

  Future<bool> checkIsAndroid() async {
    AndroidDeviceInfo androidDeviceInfo = await DeviceInfoPlugin().androidInfo;
    return androidDeviceInfo.version.sdkInt >= 33;
  }
}
